/*
回调

2021-10-04
*/

package ding

import (
	"encoding/json"
	universal "fjj/tool/universal"
	"fmt"
	"io/ioutil"

	"github.com/gin-gonic/gin"
)

// 钉钉注册信息
type register_back struct {
	AesKey      string   `json:"aes_key"`
	CallBackTag []string `json:"call_back_tag"`
	URL         string   `json:"url"`
	Token       string   `json:"token"`
}

/*
注册回调（旧）(example)

	thingTag := []string{"bpms_task_change", "user_leave_org"}
	uDing.RegisterBack(thingTag, c)
*/
func RegisterBack(thingTag []string, c *gin.Context) {
	ack := GetAccessToken()
	url := fmt.Sprintf("https://oapi.dingtalk.com/call_back/register_call_back?access_token=%s",
		ack)
	rUp := register_back{
		AesKey:      cfg.Ding.Aes_key,
		CallBackTag: thingTag,
		URL:         cfg.Ding.Url,
		Token:       cfg.Ding.Tokens,
	}
	body, _ := json.Marshal(&rUp)
	strBody := string(body[:])

	//fmt.Println(strBody)
	//fmt.Println(reflect.TypeOf(body))

	universal.GinPost(&url, &strBody, c)
}

/*
查询回调
*/
func QueryBack(c *gin.Context) {
	ack := GetAccessToken()
	url := fmt.Sprintf("https://oapi.dingtalk.com/call_back/get_call_back?access_token=%s",
		ack)
	universal.GinGet(&url, c)
}

/*
更新回调(example)

	thingTag:=[]string{"bpms_task_change", "user_leave_org"}
	uDing.UpdateBack(thingTag, c)
*/
func UpdateBack(thingTag []string, c *gin.Context) {
	ack := GetAccessToken()
	url := fmt.Sprintf("https://oapi.dingtalk.com/call_back/update_call_back?access_token=%s",
		ack)
	rUp := register_back{
		AesKey:      cfg.Ding.Aes_key,
		CallBackTag: thingTag,
		URL:         cfg.Ding.Url,
		Token:       cfg.Ding.Tokens,
	}
	body, _ := json.Marshal(&rUp)
	strBody := string(body[:])

	//fmt.Println(str_body)
	//fmt.Println(reflect.TypeOf(body))
	universal.GinPost(&url, &strBody, c)

}

/*
删除回调
*/
func DeleteBack(c *gin.Context) {
	ack := GetAccessToken()
	url := fmt.Sprintf("https://oapi.dingtalk.com/call_back/delete_call_back?access_token=%s",
		ack)
	universal.GinGet(&url, c)
}

/*
回调响应
*/
func ResponseBack(c *gin.Context) {
	//取GET请求参数
	signature := c.Query("signature")
	timestamp := c.Query("timestamp")
	nonce := c.Query("nonce")

	//fmt.Printf("signature:%s  timestamp:%s  nonce:%s", signature, timestamp, nonce)

	//取POST请求参数
	type result struct {
		Encrypt string `json:"encrypt"`
	}
	var res result
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		fmt.Printf("获取失败：%s", err)

	} else {
		//fmt.Printf("JSON:：%s\n", body)
		data := []byte(string(body))
		err = json.Unmarshal(data, &res)
		//fmt.Printf("Encrypt:%s", res.Encrypt)
	}

	//处理事项并生成SUCCESS

	newC := NewDingTalkCrypto(cfg.Ding.Tokens, cfg.Ding.Aes_key, cfg.Ding.CorpId)
	msg, _ := newC.GetEncryptMsg("success")
	//fmt.Println(msg)
	success, _ := newC.GetDecryptMsg(signature, timestamp, nonce, res.Encrypt)
	//fmt.Println("解密后JSON:", success)
	mapS := universal.JsonToMap(&success)
	value, ok := mapS["EventType"]
	if ok == true {
		switch value {
		case "check_url":
			fmt.Println("测试回调URL,返回SUCCESS")
			c.JSON(200, msg)
		default:
			fmt.Println("待定处理事项")
			c.JSON(200, msg)
		}
	} else {
		fmt.Println("回调MAP转换失败")
	}
}
